package cn.hiapi.shopkeeper.service.order;

import cn.hiapi.basic.exception.BasicException;
import cn.hiapi.basic.service.AbsBasicService;
import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.shopkeeper.entity.activity.ActivityCard;
import cn.hiapi.shopkeeper.entity.order.ActivityCardOrder;
import cn.hiapi.shopkeeper.entity.order.ActivityOrder;
import cn.hiapi.shopkeeper.jpa.order.ActivityCardOrderJpa;
import cn.hiapi.shopkeeper.service.activity.ActivityCardService;
import cn.hiapi.shopkeeper.service.activity.ActivityCodeRecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author AdinZ
 * @date 2023/1/2 12:15
 */
@Service
public class ActivityCardOrderService extends AbsBasicService<ActivityCardOrderJpa, ActivityCardOrder, Long> {

    private final DispatchContext dispatchContext;

    public ActivityCardOrderService(DispatchContext dispatchContext) {
        this.dispatchContext = dispatchContext;
    }

    /**
     * 订单支付成功,回调次卡服务
     *
     * @param order
     */
    @Transactional
    public void payCallback(ActivityOrder order) {
        ActivityCard card = this.dispatchContext.getServiceOne(ActivityCardService.class).getByAid(order.getAid());
        if (card == null) throw new BasicException("次卡服务不存在");

        ActivityCardOrder cardOrder = new ActivityCardOrder();
        cardOrder.setColor(card.getColor());
        cardOrder.setBuyerId(order.getBuyerId());
        cardOrder.setNumber(card.getNumber());
        cardOrder.setAid(order.getAid());
        cardOrder.setOid(order.getId());
        cardOrder.setShopId(order.getShopId());
        cardOrder.setUseStart(order.getUseStart());
        cardOrder.setUseEnd(order.getUseEnd());
        cardOrder.setTitle(card.getTitle());
        cardOrder.setPrice(card.getPrice());
        cardOrder.setCostPrice(order.getCostPrice());
        this.save(cardOrder);
        this.dispatchContext.getServiceOne(ActivityCodeRecordService.class).createCode(order.getId(), cardOrder.getId(), order.getBuyerId(), card);
    }
}
